package org.hr.organisation

import org.hr.xtime.AbsenceService;

class OrganisationService {

	static transactional = false
	
	UserDetails getUserDetails(def userId){
		return convert(getUserByUserId(userId))
	}

	UserDetails getBoss(def userId) {
		DummyUser user = getUserByUserId(userId)?.boss
		return convert(user)
	}

	List<UserDetails> getTeam(def userId){
		List team = []
		DummyUser.findAllByBoss(getUserByUserId(userId)).each{
			team.add(convert(it))
		}
		return team
		
	}

	List<UserDetails> getSiblings(def userId){
		return getTeam(getBoss(userId).userId)
	}
	
	private DummyUser getUserByUserId(def userId){
		def l = DummyUser.findAllByUserId(userId)
		if (l.size==0) return null
		else return l.first()
	}
	
	private UserDetails convert(DummyUser u){
		if(u != null){
			UserDetails user = new UserDetails([
				firstname:u.firstname,
				lastname:u.lastname, 
				userId:u.userId,
				bossId:u.boss?.userId
				])
			return user
		}else {
			return null
		}
	}

	def generateDummyOrgStructure(int levels, int teamSize, DummyUser boss){
		if(levels == 0){return}
		if (boss==null){
			boss = new DummyUser([
	           userId:"1",
	           firstname:"Big",
	           lastname:"Boss",
	           boss:null]).save(failOnError:true)
		} 
		(0..teamSize-1).each{it ->
			DummyUser user = new DummyUser([
						userId:"${10 * boss.userId.toInteger() + it}",
						firstname:"Name${levels}",
						lastname:"Nachname${it}",
						boss:boss
					]).save(failOnError:true)
			generateDummyOrgStructure(levels-1, teamSize, user)			
		}
	}
}
